package com.winning.util.ncpquery.service.impl;

import com.alibaba.fastjson.JSON;
import com.winning.util.excelutil.common.exception.BaseException;
import com.winning.util.excelutil.util.StringUtils;
import com.winning.util.ncpquery.entity.HttpEntity;
import com.winning.util.ncpquery.entity.NcpEntity;
import com.winning.util.ncpquery.entity.RequestEntity;
import com.winning.util.ncpquery.service.NcpQueryService;
import com.winning.util.ncpquery.util.AESUtils;
import com.winning.util.ncpquery.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @作者：caopengfei
 * @时间：2020/2/15
 */
@Service
@Slf4j
public class NcpQueryServiceImpl implements NcpQueryService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private NcpEntity ncpEntity;

    Map<String,String> appKeyForAppSercret = new HashMap<>();

    private Long secretEndTime;

    @Override
    public String queryIsPersonInfo(String xm, String sfzhm,String sid,String appKey) {
        Long  timeMillis = System.currentTimeMillis();
        log.info("姓名:"+xm+" 身份证号码");
        RequestEntity requestEntity = new RequestEntity();
        requestEntity.setGjzwfwpt_sid(sid);
        requestEntity.setGjzwfwpt_rid(ncpEntity.getRid());
/*        if(secretEndTime<timeMillis){
        }*/
        //前面为空说明
        String sign = appKeyForAppSercret.get(appKey);
        if(StringUtils.isEmpty(sign)){
            requestEntity.setGjzwfwpt_rtime(timeMillis+"");
            sign = getSignKey(requestEntity,appKey);
            appKeyForAppSercret.put(appKey,sign);
            log.info("appKey:" +appKey+"; sign"+sign);
        }
        //重新更换时间戳
        requestEntity.setGjzwfwpt_rtime(System.currentTimeMillis()+"");
        requestEntity.setGjzwfwpt_sign(null);
        String body = JSON.toJSONString(requestEntity);
        log.info("数据请求体是："+body);
        //获取签名
        HttpEntity httpEntity = new HttpEntity();
        httpEntity.setUrl(ncpEntity.getQueryUrl()+"?xm"+xm+"&sfzhm="+sfzhm);
        Map<String,String> header = new HashMap<String,String>();
        header.put("gjzwfwpt_rid",requestEntity.getGjzwfwpt_rid());
        header.put("gjzwfwpt_sid",requestEntity.getGjzwfwpt_sid());
        header.put("gjzwfwpt_rtime",requestEntity.getGjzwfwpt_rtime());
        sign(requestEntity,sign);
        header.put("gjzwfwpt_sign",requestEntity.getGjzwfwpt_sign());
        httpEntity.setBody("");
        httpEntity.setHeaders(header);
        log.info("请求数据的请求体是"+JSON.toJSONString(requestEntity));
        String result = HttpUtil.sendReq(httpEntity);
        Map resultMap = JSON.parseObject(result,Map.class);
        log.info("返回结果是"+result);
        if(StringUtils.isNotEmpty(resultMap.get("code")+"")&&
                "200".equals(resultMap.get("code")+"")){
            return result;
            //说明这个前面可以
         //如果是不是说明签名有问题。获取签名重新请求
        }else{
            requestEntity.setGjzwfwpt_rtime(System.currentTimeMillis()+"");
            sign = getSignKey(requestEntity,appKey);
            appKeyForAppSercret.put(appKey,sign);
            sign(requestEntity,sign);
            header.put("gjzwfwpt_sign",requestEntity.getGjzwfwpt_sign());
            String result2 =  HttpUtil.sendReq(httpEntity);
            log.info("返回结果2是"+result2);
            return result2;
        }
    }


    /**
    * @vsts_no：
    * @comment： 获取签名
    * @author： caopengfei
    * @time：  2020/2/15 21:22
    */
    private String  getSignKey(RequestEntity requestEntity,String appKey){
        //首先使用appKey生成签名
        sign(requestEntity,appKey);
        HttpEntity httpEntity = new HttpEntity();
        httpEntity.setUrl(ncpEntity.getAppSecretUrl());
        String body = JSON.toJSONString(requestEntity);
        httpEntity.setBody(body);
        log.info("获取签名的响应信息是信息"+body);
        String result = HttpUtil.sendReq(httpEntity);
        log.info("获取签名的响应信息是信息"+result);
        Map<String,Object>  resultMap = JSON.parseObject(result,Map.class);
        if("0".equals(resultMap.get("code"))){
            Map<String,Object> data = (Map<String, Object>) resultMap.get("data");
            //获取秘钥
            String secret = (String) data.get("secret");

            log.info("secret："+secret);
            if(data.get("secret") != null){
                secretEndTime = Long.parseLong(data.get("secretEndTime")+"");
                //对秘钥进行解密,获取到真正的秘钥
                String signKey = AESUtils.AESDncode(appKey,secret);
                log.info("解密后的签名是："+signKey);
                return signKey;
            }else{
                throw new BaseException("获取的签名secret不存在");
            }
        }else{
            throw new BaseException("获取签名失败");
        }
    }

     /**
     * @vsts_no：
     * @comment： 重新刷新秘钥
     * @author： caopengfei
     * @time：  2020/2/15 19:41
     */
    private void sign(RequestEntity requestEntity,String key){
        String content = requestEntity.getGjzwfwpt_sid()+requestEntity.getGjzwfwpt_rid()+requestEntity.getGjzwfwpt_rtime();
        String signTemp = AESUtils.sign(content,key);
        requestEntity.setGjzwfwpt_sign(signTemp);
    }
}
